﻿using System.Collections.Generic;
using System.Linq;
using UnityEngine.EventSystems;

namespace JH
{
    public static class GetFirstEventHandleRealization
    {
        /// <summary>
        ///  返回第一个找到的IEventSystemHandler
        /// </summary>
        /// <param name="raycaster">方便调用提供的扩展，并无实际含义</param>
        /// <param name="list">射线投射结果</param>
        /// <typeparam name="T">首个找到的目标事件句柄</typeparam>
        /// <returns>找到目标事件句柄则返回，否则返回default</returns>
        public static RaycastResult GetFirstHandleEm<T>(this BaseRaycaster raycaster, List<RaycastResult> list)
            where T : IEventSystemHandler
        {
            if (list == null || list.Count == 0) return default;

            //投射结果排序
            list.Sort(raycaster.RaycastComparerEm);

            foreach (var each in from each in list
                     where each.gameObject
                     let comp = each.gameObject.GetComponent<T>()
                     where comp != null
                     select each)
            {
                return each;
            }

            return default;
        }
    }
}